import React, { Component, PropTypes } from 'react';
import Echarts from 'echarts';
import { connect } from 'dva'
import {
  Input,
  Button,
  Select,
  Form,
  Modal,
  Row,
  Col,
  Icon,
  message,
  Calendar
} from 'antd';
const { TextArea } = Input;
import Style from './home.less';
import NumberPlay from '../../util/numberPlay';
import $ from 'jquery';
import Service from "../../service";
import Moment from 'moment';
const FormItem = Form.Item;
const createForm = Form.create;
const Option = Select.Option;
const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      page: 1,
      pageSize: 10,
      searchValue: '',
      isCalender: false,
      videList: [],
      calandarValue: '',
      calandarText: ''
    };
  }
  componentDidMount() {
    let self = this;
    const token = localStorage.getItem('token');
    self.expressindexFun();
    $(window).scroll(function () {
      // console.log(4444)
      let totalNum = self.props.totalPage;
      let currentNum = self.state.page * self.state.pageSize;
      // console.log($(window).scrollTop() + $(window).height())
      // console.log( $(document).height())
      if ($(window).scrollTop() + $(window).height() == $(document).height()) {
        // console.log(111)
        // console.log(self.props.SMore)
        if (self.props.SMore) {
          self.pageMore(self.state.page);
        }

      }
    });
  }
  componentWillUnmount() {
    if (this.state.timer != null) {
      clearInterval(this.state.timer);

    }
  }
  expressindexFun = (mobile) => {
    let self = this;
    const token = localStorage.getItem('token');
    self.props.expressindex({
      params: {
        token: token,
        page: self.state.page,
        pageSize: self.state.pageSize
        // status: 0,
      },
      func: function (result) {
        if (result && result.total_page > 1) {
          pageMoreW = true
          // self.setState({
          //   videList: result.list
          // })
        }

      }
    })
    self.setState({
      page: 1
    })

  }
  pageMore = (page) => {
    let self = this;
    const token = localStorage.getItem('token');
    self.setState({
      page: page + 1
    }, function () {
      self.props.expressindex({
        params: {
          token: token,
          page: self.state.page,
          limit: self.state.pageSize
        },
        func: function (data) {

        }
      })
      // console.log(this.state.page);
      // this.props.queryList({ token: token, level: this.state.level, id: this.state.id,keywords:this.state.keywords,page:this.state.page,pageSize:this.state.pageSize });
    });

  }
  onPanelChange = (value, mode) => {
    let self = this;
    const token = localStorage.getItem('token');
    let t = Moment(value)
      .format('YYYY-MM');
    let r = Moment(value)
      .format('dd');

    let Timestamp = Moment(value).format('X'); // 获取时间戳
    self.setState({
      calandarText: t,
      isCalender: false
    })

    self.props.expressindex({
      params: {
        token: token,
        date: Timestamp,
        page: 1,
        pageSize: self.state.pageSize
      },
      func: function (result) {
        if (result) {
          self.setState({
            videList: result.list
          })
        }

      }
    })


  }
  calenderFun = () => {
    let self = this;
    if (self.state.isCalender) {
      self.setState({
        isCalender: false
      })
    } else {
      self.setState({
        isCalender: true
      })
    }

  }
  editFun = () => {
    this.context.router.push(`/1/app/editMy`);
  }
  lasturlFun = () => {
    this.context.router.push(`/1/app/kindex`);
  }
  carlocationurlFun = () => {
    this.context.router.push(`/1/app/carlocation`);
  }
  homeurlFun = () => {
    this.context.router.push(`/1/app/kmy`);
  }
  //  进入详情
  detailFun = (record) => {
    // if (record && record.status == 0) {
    //   this.props.saveVideoStatus(record)
    //   this.context.router.push(`/1/app/kindex`);
    // }
  }
  openFun = () => {
    let self = this;
    let token = localStorage.getItem('token');
    let v = self.state.selectVal;
    if (!v) {
      message.error('请选择电动车');
    }
    self.setState({
      loading: 'block'
    })
    self.props.update({
      params: {
        devices_id: v,
        status: 'open',
        token: token
      },
      func: function (data) {
        if (data) {
          self.state.timerNum = 0;
          self.state.timer = setInterval(() => {
            self.state.timerNum++;
            if (self.state.timerNum >= 8) {
              self.setState({
                loading: 'none'
              })
              clearInterval(self.state.timer);
            }
            self.receiveFun(data.data, 1);
          }, 4000)

        }
      }
    })

  }
  receiveFun = (uuid, type) => {
    let self = this;
    let token = localStorage.getItem('token');
    let params = { 'uuid': uuid, 'token': token };
    $.ajax({
      url: `${Service.baseUrl}/devices/receive`,   //列表
      type: 'POST',
      data: params,
      success: function (data) {
        if (data.code == 200) {
          if (self.state.timer != null) {
            clearInterval(self.state.timer);
          }
          self.setState({
            loading: 'none'
          })
          if (data.data.status == 1) {
            if (type == 1) {
              message.success('开启成功!', 1.5);
            } else {
              message.success('关闭成功!', 1.5);
            }
          } else {
            if (type == 1) {
              message.error('开启失败!', 1.5);
            } else {
              message.error('关闭失败!', 1.5);
            }
          }

        } else {
          if (self.state.timerNum >= 8) {
            message.error(data.error, 1.5);
          }
        }
      }.bind(this),
      error: function (xhr, status, err) { }.bind(this)
    })
  }
  closeFun = () => {
    let self = this;
    let token = localStorage.getItem('token');
    let v = self.state.selectVal;
    if (!v) {
      message.error('请选择电动车');
    }
    self.setState({
      loading: 'block'
    })
    self.props.update({
      params: {
        devices_id: v,
        status: 'close',
        token: token
      },
      func: function (data) {
        if (data) {
          self.state.timerNum = 0;
          self.state.timer = setInterval(() => {
            self.state.timerNum++;
            if (self.state.timerNum >= 6) {
              self.setState({
                loading: 'none'
              })
              clearInterval(self.state.timer);
            }
            self.receiveFun(data.data, 2);
          }, 5000)

        }
      }
    })
  }
  // 发送
  sendSubmit = () => {
    Modal.success({
      title: '提交成功',
      content: '',
      okText: '确定'
    });
  }
  // 视频清单
  videoListFun = () => {
    this.context.router.push(`/1/app/kvideolist`);
  }
  searchValueFun = (e) => {
    var v = e.target.value;
    this.setState({
      searchValue: v
    })
  }
  searchValueSubmitFun = () => {
    let self = this;
    let searchValue = self.state.searchValue;
    let token = localStorage.getItem('token');
    self.props.expressindex({
      params: {
        token: token,
        status: searchValue,
        page: 1,
        pageSize: self.state.pageSize
      },
      func: function (result) {
        if (result) {
          self.setState({
            videList: result.list
          })
        }

      }
    })
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const { data, videList } = this.props;
    let vehicleData = data || [];
    // console.log(videList);
    // console.log(this.props);
    return (
      <div className={Style.wrap}>
        <div className={Style.headWrap}>
          <div className={Style.navTitle}>
            最后一公里
            <span className={Style.arrowEdit} onClick={this.videoListFun}>视频清单</span>

          </div>
        </div>
        <div className={Style.dataWrap}>
          <div className={Style.filxtitlewrap}>
            <div className={Style.filterTitle + ' ' + Style.filterTitle1}>
              <FormItem label='搜索视频:' {...formItemLayout}>
                {getFieldDecorator('name', {
                  // initialValue: Statistics && Statistics.age || '',
                })(
                  <Input onChange={this.searchValueFun} onBlur={this.searchValueSubmitFun} value={this.state.searchValue} />
                  )}
              </FormItem>

            </div>
            <div className={Style.filterTitle}>
              按日期筛选：{this.state.calandarText}<Icon onClick={this.calenderFun} type="calendar" style={{ fontSize: '20px', color: '#000' }} />
              {this.state.isCalender &&
                <div className={Style.filterCalender}>
                  <Calendar fullscreen={false} onSelect={this.onPanelChange} />
                </div>
              }

            </div>
          </div>
          <div className={Style.videolistWrap}>
            <div className={Style.filterItem}>
              {videList && videList.map((item, index) => {
                // console.log(item)
                return (
                  <dl onClick={this.detailFun.bind(this, item)}>
                    <dt>
                      <video src={`${Service.qiniuUrl}/` + item.video} width="320" height="240" controls="controls">
                        Your browser does not support the video tag.
          </video>
                    </dt>
                    <dd>
                      <p className={Style.linebd}>快递员手机号:{item.e_bike_mobile}</p>
                      <p>发送时间：{Moment(item.createtime * 1000).format("YYYY/MM/DD HH:mm:ss")}</p>
                      <div className={Style.status}>
                        <Icon type="check-square" /> 签收状态：{item.status_text}
                      </div>
                      <p><span className={Style.rateIcon}></span>此次服务评价：
                    {item.star && "好评"}
                        {!item.star && "无"}
                      </p>
                    </dd>
                    {item.refuse &&
                      <div className={Style.commentWrap}>
                        <TextArea rows={5} value={item.refuse} placeholder="补充描述" />
                      </div>
                    }
                  </dl>
                )
              })}
              {/* <dl>
                <dt>
                <video src="movie.ogg" width="320" height="240" controls="controls">
          Your browser does not support the video tag.
          </video>
                </dt>
                <dd>
                  <p className={Style.linebd}>用户：000000</p>
                  <p>发送时间：2019/02/04 12:12:12</p>
                    <div className={Style.status}>
                    <Icon type="check-square" /> 签收状态：无
                    </div>
                    <p><span className={Style.rateIcon}></span>此次服务评价：无</p>


                </dd>
               
              </dl>
              <dl>
                <dt>
                <video src="movie.ogg" width="320" height="240" controls="controls">
          Your browser does not support the video tag.
          </video>
                </dt>
                <dd>
                  <p className={Style.linebd}>用户：000000</p>
                  <p>发送时间：2019/02/04 12:12:12</p>
                    <div className={Style.status}>
                    <Icon type="check-square" /> 签收状态：无
                    </div>
                    <p><span className={Style.rateIcon}></span>此次服务评价：无</p>

                </dd>
                <div className={Style.commentWrap}>
                  <TextArea  rows={5} placeholder="补充描述"/>
                </div>              
                </dl>
                <dl>
                <dt>
                <video src="movie.ogg" width="320" height="240" controls="controls">
          Your browser does not support the video tag.
          </video>
                </dt>
                <dd>
                  <p className={Style.linebd}>用户：000000</p>
                  <p>发送时间：2019/02/04 12:12:12</p>
                    <div className={Style.status}>
                    <Icon type="check-square" /> 签收状态：无
                    </div>
                    <p>理由：其他原因</p>
                </dd>
                <div className={Style.commentWrap}>
                  <TextArea  rows={5} placeholder="补充描述"/>
                </div>              
                </dl> */}
            </div>
          </div>
        </div>

        <div className={Style.foot}>
          <Row type="flex">
            <Col span={8} order={1} className={Style.on} onClick={this.lasturlFun}>
              <Icon style={{ fontSize: 20 }} type="heart" theme="outlined" /><p>最后一公里</p>
            </Col>
            <Col span={8} order={2} onClick={this.carlocationurlFun}>
              <Icon style={{ fontSize: 20 }} type="environment" theme="outlined" /><p>车辆位置</p>
            </Col>
            <Col span={8} order={2} onClick={this.homeurlFun}>
              <Icon style={{ fontSize: 20 }} type="user" theme="outlined" /><p>我的</p>
            </Col>
          </Row>
        </div>
        <div className={Style.marsk} style={{ display: this.state.loading }}>
          <Icon type="loading" className={Style.loading} />
          <p className={Style.loadText}>请耐心等待...</p>
        </div>
      </div>
    )
  }
}

App.contextTypes = {
  router: React.PropTypes.object
}

function mapStateToProps(state, ownProps) {
  // console.log(state)
  return {
    data: state.vehicle.data,
    videList: state.kmodel.Slist,
    SMore: state.kmodel.SMore,
    loading: !!state.loading.global
  }
}

function dispatchToProps(dispatch) {
  return {
    expressindex(payload, params) {
      dispatch({
        type: 'kmodel/expressindex',
        payload
      })
    },
    saveVideoStatus(payload, params) {
      dispatch({
        type: 'kmodel/saveVideoStatus',
        payload
      })
    },
  }
}
export default connect(mapStateToProps, dispatchToProps)(Form.create()(App));
